//app.js
import GetAudioUrl from './utils/audio.js'
const config = require('config/config');
const storage = require('utils/cache.js');
const getAudio = new GetAudioUrl()
var backgroundAudioManager
App({
  onLaunch: function (options) {
    try {
      let res = wx.getSystemInfoSync();
      config.pixelRate = res.windowWidth / 750;
      config.platform = res.platform;
      config.statusBarHeight = res.statusBarHeight;
      if (res.platform.toLowerCase() == 'android') {
        config.capsuleHeight += 4;
      }
      config.titleHeight = (config.capsuleHeight + config.statusBarHeight) / config.pixelRate;
      if (res.statusBarHeight >= 44) {
        config.isHighHead = true;
      }
      if (res.windowHeight > 750) config.isAllScreen = true;
      config.systemHeight = res.windowHeight;
    } catch (e) {
      console.log(e);
    }
  },
  globalData: {
    gift: null,
    is_pay: null,
    isPlay: false,
    isPay: false,
    shareNum: 5
  },
  play() {
    wx.getSavedFileList({
      success(res) {
        let url = res.fileList[0].filePath
        // that.playAudio(res.fileList[0].filePath)
        backgroundAudioManager = wx.getBackgroundAudioManager()
        // 设置了 src 之后会自动播放
        backgroundAudioManager.title = "天天音乐";
        backgroundAudioManager.src = url;
        backgroundAudioManager.play();
        backgroundAudioManager.onPlay(() => {
          console.log('音乐播放')
        })
        backgroundAudioManager.onEnded(() => {
          console.log("音乐播放结束");
          backgroundAudioManager.play()
        })
        backgroundAudioManager.onPause(() => {
          console.log('音乐暂停了')
        })
      }
    })
    
  },
  onShow(options) {
    if (options.id) {
    } else {
      let that = this
      wx.downloadFile({
        url: 'https://pic.dong20.com/wx/yeargift/music/bg_music.mp3', // 仅为示例，并非真实的资源
        success(res) {
          // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
          if (res.statusCode === 200) {
            const tempFilePath = res.tempFilePath
            wx.getSavedFileList({
              success(res) {
                if (res.fileList.length == 0) {
                  wx.saveFile({
                    tempFilePath: tempFilePath,
                    success(res) {
                      that.play()
                    }
                  })
                } else {
                  that.play()
                }
              }
            })
          }
        }
      })
    }
  },
  onHide() {
    backgroundAudioManager.stop()
  }
})